package netty.bio;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Server {

    private static final int PORT = 8900;

    private static ServerSocket serverSocket;

    private static ExecutorService executorService = Executors.newFixedThreadPool(5);

    public static void start() throws IOException {
        serverSocket = new ServerSocket(PORT);
        System.out.println("服务器已启动；端口：" + PORT);
        try {
            while (true) {
                Socket socket = serverSocket.accept();
                executorService.execute(new ServerHandler(socket));
            }
        } finally {
            if (null != serverSocket) {
                serverSocket.close();
            }
        }
    }

    public static void main(String[] args) throws IOException {
        start();
    }

    public static class ServerHandler implements Runnable {

        private Socket socket;

        public ServerHandler(Socket socket) {
            this.socket = socket;
        }

        @Override
        public void run() {
            try (BufferedReader br = new BufferedReader(
                    new InputStreamReader(socket.getInputStream()));
                 PrintWriter writer = new PrintWriter(socket.getOutputStream())) {
                String msg = null;
                while ((msg = br.readLine()) != null) {
                    System.out.println("Server accept message: " + msg);
                    writer.println(String.format("Hello, %s Now is %s", msg, new Date().toString()));
                    writer.flush();
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            } finally {
                if (null != socket) {
                    try {
                        System.out.println("Server accept socket closed");
                        socket.close();
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        }
    }
}
